const UserService = require("../../services/admin/UserService");
const jwt = require("jsonwebtoken");

const UserController = {
  login: async (req, res) => {
    const result = await UserService.login(req, res);
    if (result.length === 0) {
      res.status(401).json({
        code: 0,
        msg: "登录失败",
        data: {},
      });
    } else {
      const id = result[0]["_id"].toString();
      const token = jwt.sign({ id }, "secret", {
        expiresIn: "1h",
      });
      res.json({
        code: 1,
        msg: "登录成功",
        data: {
          token: token,
        },
      });
    }
  },

  upload: async (req, res) => {
    const { authorization } = req.headers;
    jwt.verify(authorization, "secret", async (err, decode) => {
      const result = await UserService.upload(req.file, decode.id);
      if (result) {
        res.json({
          code: 1,
          msg: "上传成功",
          data: {
            url: result,
          },
        });
      }
    });
  },

  addUser: async (req, res) => {
    const result = await UserService.addUser(req, res);
    if (result) {
      res.json({
        code: 1,
        msg: "添加成功",
        data: {},
      });
    }
  },

  getInfo: async (req, res) => {
    const { authorization } = req.headers;
    jwt.verify(authorization, "secret", async (err, decode) => {
      const result = await UserService.getInfo(decode.id);
      if (result) {
        res.json({
          code: 1,
          msg: "获取成功",
          data: result,
        });
      }
    });
  },

  edit: async (req, res) => {
    const { authorization } = req.headers;
    jwt.verify(authorization, "secret", async (err, decode) => {
      const result = await UserService.edit(decode.id, req.body, req.file);
      if (result) {
        res.json({
          code: 1,
          msg: "修改成功",
          data: result,
        });
      }
    });
  },

  delete: async (req, res) => {
    const { authorization } = req.headers;
    jwt.verify(authorization, "secret", async (err, decode) => {
      const id = decode.id;
      const result = await UserService.delete(id);
      if (result) {
        res.json({
          code: 1,
          msg: "删除成功",
          data: result,
        });
      }
    });
  },

  getAllUser: async (req, res) => {
    const result = await UserService.getAllUser(req, res);
    res.json({
      code: 1,
      msg: "获取成功",
      data: result,
    });
  },
};
module.exports = UserController;
